package com.bibi.zoo.service;

import com.baidu.aip.ocr.AipOcr;
import com.bibi.zoo.pkg.req.ReqLogin;
import com.bibi.zoo.pkg.resp.*;
import com.bibi.zoo.web.req.ReqBuy;
import com.bibi.zoo.web.req.ReqInput;
import com.google.common.collect.*;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class HandleService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private RestTemplate restTemplate;


    public void getLuckkey(ReqInput req) {
        try {
            RespVerifyCode respVerifyCode;
            Integer code;
            while(true) {
                //获取验证码
                respVerifyCode = getCodeUrl();
                if(respVerifyCode == null) {
                    continue;
                }
                //识别验证码
                code = getCode(respVerifyCode.getData().getUrl());
                if(code != null) {
                    break;
                }
            }
            //登录
            RespLogin loginRes = login(respVerifyCode, code,req);
            String luckkey = loginRes.getData();
            HttpHeaders authHeaders = new HttpHeaders();
            authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
            authHeaders.add("luckkey",luckkey);
            authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            if(!StringUtils.isEmpty(luckkey)) {
                Constants.luckkeyMap.put(req.getPhone(),luckkey);
                //获取个人信息
                HttpEntity<String> requestEntity = new HttpEntity<>(null, authHeaders);
                RespUserInfo respUserInfo = restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/assets/findUserAssetsByUser", requestEntity, RespUserInfo.class);
                logger.info("用户信息：{}", com.alibaba.fastjson.JSONObject.toJSONString(respUserInfo));
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public boolean inviteZoo(ReqBuy req) {
        String luckkey = Constants.luckkeyMap.get(req.getPhone()).get(0);
        HttpHeaders authHeaders = new HttpHeaders();
        authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
        authHeaders.add("luckkey",luckkey);
        authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return invite(authHeaders,req);
    }

    public void buy(ReqBuy req,long deadTime) {
        String luckkey = Constants.luckkeyMap.get(req.getPhone()).get(0);
        HttpHeaders authHeaders = new HttpHeaders();
        authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
        authHeaders.add("luckkey",luckkey);
        authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        flushBuy(authHeaders,req,deadTime);
    }

    public RespCheckGame checkGame(String phone) {
        String luckkey = Constants.luckkeyMap.get(phone).get(0);
        HttpHeaders authHeaders = new HttpHeaders();
        authHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
        authHeaders.add("luckkey",luckkey);
        authHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, authHeaders);
        try {
            return restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/game/checkGame", requestEntity, RespCheckGame.class);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    ExecutorService pool = Executors.newCachedThreadPool();
    public void flushBuy(HttpHeaders authHeaders,ReqBuy req,long deadTime) {
        for(int i=0; i<2;i++) {
            pool.execute(() -> {
                while (System.currentTimeMillis() < deadTime) {
                    HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
                    Map<String,Object> params = new HashMap<>();
                    params.put("id",req.getZid());
                    BaseResp baseResp = restTemplate.postForObject("http://luck9.luckyzodiac12.com/api/game/flash_buy/{id}", requestEntity2, BaseResp.class,params);
                    logger.info("phone:{},抢购结果：{}", req.getPhone(),com.alibaba.fastjson.JSONObject.toJSONString(baseResp));
                }
            });
        }
        pool.execute(() -> {
            while (System.currentTimeMillis() < deadTime) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
                Map<String,Object> params = new HashMap<>();
                params.put("id",req.getZid());
                ResponseEntity<BaseResp> exchange = restTemplate.exchange("http://luck9.luckyzodiac12.com/api/game/checkOpen/{id}", HttpMethod.GET, requestEntity2, BaseResp.class, params);
                logger.info("phone:{},开奖结果:{}",req.getPhone(),com.alibaba.fastjson.JSONObject.toJSONString(exchange.getBody()));
            }
        });
    }

    public boolean invite(HttpHeaders authHeaders,ReqBuy req) {
        HttpEntity<String> requestEntity2 = new HttpEntity<>(null, authHeaders);
        Map<String,Object> params = new HashMap<>();
        params.put("id",req.getZid());
        try {
            BaseResp baseResp = restTemplate.exchange("http://luck9.luckyzodiac12.com/api/pigInvitation/invitation/{id}", HttpMethod.GET,requestEntity2, BaseResp.class,params).getBody();
            logger.info(com.alibaba.fastjson.JSONObject.toJSONString(baseResp));
            if(baseResp.getCode() != null && baseResp.getCode().equals(200)) {
                logger.info("phone:{},zid:{},预约成功",req.getPhone(),req.getZid());
                return true;
            }
            return false;
        } catch (HttpClientErrorException e) {
            logger.error("phone:{},msg:{}",req.getPhone(),e.getResponseBodyAsString());
            if(e.getResponseBodyAsString().contains("积分不足")) {
                return false;
            } else {
                return true;
            }
        }
    }

    private RespLogin login(RespVerifyCode respVerifyCode, Integer code,ReqInput req) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
        ReqLogin reqLogin = new ReqLogin();
        reqLogin.setName(req.getPhone());
        reqLogin.setPassword(req.getPwd());
        reqLogin.setRememberMe(true);
        reqLogin.setVerifyCode(code.toString());
        reqLogin.setVerifyCodeToken(respVerifyCode.getData().getToken());
        HttpEntity<ReqLogin> requestEntity = new HttpEntity<>(reqLogin, requestHeaders);
        for(int i=0;i<3;i++) {
            try{
                RespLogin respLogin = restTemplate.postForObject("http://luck9.luckyzodiac12.com/auth/login", requestEntity, RespLogin.class);
                return respLogin;
            }catch (HttpClientErrorException e) {
                logger.error(e.getResponseBodyAsString());
            }
        }
        return null;
    }

    private RespVerifyCode getCodeUrl() {
        try {
            return restTemplate.getForObject("http://luck9.luckyzodiac12.com/api/verifyCode/get", RespVerifyCode.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //设置APPID/AK/SK
    public static final String APP_ID = "16671499";
    public static final String API_KEY = "hYRzxXysp0FDcmZBWXOlPLFY";
    public static final String SECRET_KEY = "kYf0vaVh3EZwlRvwcGYudKMFXrFYaxcO";
    public static AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    public Integer getCode(String codeUrl) {
        byte[] bytes = getCodeBytes(codeUrl);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        HashMap<String, String> options = new HashMap<>();
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        try {
            JSONObject jsonObject = client.webImage(bytes, options);
            String code = jsonObject.getJSONArray("words_result").getJSONObject(0).getString("words");
            if(code.length() == 4) {
                return Integer.parseInt(code);
            }
        } catch (Exception e) {
            logger.error("baidu getCode error:{}",e.getMessage());
        }
        return null;
    }

    public byte[] getCodeBytes(String codeUrl) {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        byte[] bytes = null;
        try {
            bytes = base64Decoder.decodeBuffer(codeUrl);
            /*FileOutputStream fos = new FileOutputStream("code.jpeg");
            fos.write(bytes);
            fos.close();*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }
}
